<template>
  <div style="display: inline-block;margin: auto 16px">
    <el-upload
      class="avatar-uploader"
      :action="qiniuUrl"
      :data="postData"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :on-success="handleAvatarSuccess"
      :on-remove="handleRemove"
      :http-request="qiniuRequest"
      :disabled="imageLoading">
      <div class="upload-box" @click="fileClick()">
        <el-button type="primary" :loading="imageLoading">{{buttonTitle}}</el-button>
      </div>
    </el-upload>
  </div>
</template>

<script>
  import * as qiniuAPI from '@/api/qiniu'
  import * as commonAPI from '@/api/common'
  import { parseTime } from '@/filters'
  import lrz from 'lrz'
  export default {
    name: 'image_upload',
    props: {
      // 七牛返回结果
      qiniu_res: {
        type: Array,
        default: function() {
          return []
        }
      },
      // 按钮的标题
      buttonTitle: {
        type: String,
        default: function() {
          return '上传图片'
        }
      },
      // 图片的正反面 （01-正面 02-反面 03-手持照）
      attachType: {
        type: String,
        default: function() {
          return '01'
        }
      },
      // 当前上传是否激活
      disabled: {
        type: Boolean,
        default: function() {
          return false
        }
      },
      // 司机，承运商...
      type_code: {
        type: String,
        default: function() {
          return ''
        }
      },
      // 附件的类型
      license_type_id_code: {
        type: Number,
        default: function() {
          return null
        }
      },
      // 附件的类型
      id_code: {
        type: Number,
        default: function() {
          return null
        }
      },
      // 附件的类型
      type: {
        type: String,
        default: function() {
          return ''
        }
      },
      // 将要上传到数据库的mergeData
      mergeData: {
        type: Object,
        default: function() {
          return {
            name: ''
          }
        }
      }
    },
    data() {
      return {
        imageLoading: false,
        name: '',
        postData: {
          token: ''
        },
        fileList: [],
        currentFile: '',
        imageUrl: '',
        currentFileSize: 0,
        licenseDistinguishInfo: {},
        licenseTypeId: null,
        type_temp: ''
      }
    },
    mounted() {
    },
    methods: {
      // 获取证件的licenseId
      getLicenseId() {
        const a = this.type
        const id_t = a.replace('lic', '')
        const reg = /^0/g
        if (a && reg.test(id_t)) {
          this.licenseTypeId = parseInt(a.replace('lic0', ''))
        } else {
          this.licenseTypeId = parseInt(a.replace('lic', ''))
        }
      },
      // 选择文件时 获取token
      fileClick() {
        const that = this
        that.currentFile = ''
        qiniuAPI.getToken().then(res => {
          that.postData.token = res.data
        }).catch(err => {
          console.log(err)
        })
      },
      // 上传文件前 做一些大小和文件格式校验
      beforeAvatarUpload(file) {
        // 获取证照id
        this.getLicenseId()
        // 图片本地预览地址
        this.imageUrl = URL.createObjectURL(file)
        // 当前选中文件对象
        this.currentFile = file
        // 当前文件大小， 因为后面要压缩，这里设置为0即可， 压缩后补加进来
        this.currentFileSize = 0
        // 验证图片的大小的格式是否合法
        const a = this.tools.authImage(file)
        this.imageLoading = true
        if (!a) {
          this.imageLoading = false
        }
        return a
      },
      /**
       * 图片上传成功后
       * @param res  页面展示需要的数据
       * @param file 七牛返回文件的详细信息
       */
      handleAvatarSuccess(res, file) {
        const that = this
        file.raw = {
          type: file.type,
          size: that.currentFileSize
        }
        res.hash = res.data.hash
        file.url = this.imageUrl
        this.imageLoading = false
        // res.key = file.name
        // res.name = file.name
        //
        res.key = res.data.key
        res.name = file.name
        //
        res.format = file.raw.type
        res.uploadTime = new Date().getTime()
        res.size = file.raw.size
        res.attachType = this.attachType
        res.lookUrl = file.url
        console.log('上传成功')
        // 拼接保存数据库的数据
        const licenseAttachList = {
          attachName: res.name,
          name: res.name,
          format: file.raw.type,
          size: file.raw.size,
          attachKey: res.hash,
          uploadTime: parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'),
          attachType: this.attachType,
          lookUrl: file.url
        }
        // 页面操作数据
        const t = {
          type: this.type,
          data: {
            res: res,
            file: file,
            licenseAttachList
          }
        }
        // 将图片上传成功信息保存数据库
        const pData = {
          ...res,
          ...this.mergeData
        }
        console.log(pData)
        this.$emit('get_data', t)
      },
      // 移除文件
      handleRemove(file, fileList) {
      },
      // 图片压缩处理
      qiniuRequest(req) {
        const that = this
        const file = req.file
        console.log('压缩前图片大小', file.size)
        lrz(file, { quality: 0.6 }).then(res => {
          const config = {
            headers: { 'Content-Type': 'multipart/form-data' }
          }
          // 将图片的大小改为压缩后的的小
          that.currentFileSize = res.file.size
          console.log('压缩后图片大小', res.file.size)
          const formData = new FormData()
          formData.append('file', res.file)
          formData.append('token', that.postData.token)
          that.$http.post(that.qiniuUrl, formData, config).then(respone => {
            /**
             * 上传成功后，获取图片的查看地址
             * 如果证照在可识别列表中并且为正面
             * 调用图片识别接口识别接口
             */
            if (that.tools.distinguishList().indexOf(that.type) !== -1) {
              // 个人省份证 和 法人身份证
              if (that.type === 'lic01' || that.type === 'lic07') {
                that.type_temp = 'licId'
              } else {
                that.type_temp = that.type
              }
              switch (that.type_temp) {
                case 'licId': {
                  // 身份证识别
                  if (that.attachType !== '03') {
                    qiniuAPI.getAttachInfo({
                      keys: [respone.data.key],
                      type: that.type_code,
                      id: that.id_code,
                      licenseTypeId: that.license_type_id_code
                    }).then(res => {
                      let type_id = null
                      that.attachType === '01' ? type_id = 1 : type_id = 2
                      const form = new FormData()
                      form.append('imgUrl', res.data[0].downloadUrl)
                      form.append('type', type_id)
                      commonAPI.identityCardInfo(form).then(res => {
                        if (res.code === 0) {
                          that.$emit('distinguish_info', {
                            licenseTypeId: that.licenseTypeId,
                            attachType: that.attachType,
                            data: res.data
                          })
                          that.$message({
                            message: '身份证识别成功',
                            type: 'success',
                            duration: 2 * 1000
                          })
                        }
                      }).catch(() => {
                        //
                      })
                    })
                  }
                  break
                }
                case 'lic02': {
                  // 驾照识别
                  if (that.attachType === '01') {
                    qiniuAPI.getAttachInfo({
                      keys: [respone.data.key],
                      type: that.type_code,
                      id: that.id_code,
                      licenseTypeId: that.license_type_id_code
                    }).then(res => {
                      const form = new FormData()
                      form.append('imgUri', res.data[0].downloadUrl)
                      commonAPI.driverlicenseinfo(form).then(res => {
                        if (res.code === 0) {
                          that.$emit('distinguish_info', {
                            licenseTypeId: that.licenseTypeId,
                            attachType: that.attachType,
                            data: res.data
                          })
                          that.$message({
                            message: '驾照识别成功',
                            type: 'success',
                            duration: 2 * 1000
                          })
                        }
                      }).catch(() => {
                        //
                      })
                    })
                  }
                  break
                }
                case 'lic10': {
                  // 行驶证
                  if (that.attachType === '01') {
                    qiniuAPI.getAttachInfo({
                      keys: [respone.data.key],
                      type: that.type_code,
                      id: that.id_code,
                      licenseTypeId: that.license_type_id_code
                    }).then(res => {
                      const form = new FormData()
                      form.append('imgUri', res.data[0].downloadUrl)
                      commonAPI.drivinglicenseinfo(form).then(res => {
                        if (res.code === 0) {
                          that.$emit('distinguish_info', {
                            licenseTypeId: that.licenseTypeId,
                            attachType: that.attachType,
                            data: res.data
                          })
                          that.$message({
                            message: '行驶证识别成功',
                            type: 'success',
                            duration: 2 * 1000
                          })
                        }
                      }).catch(() => {
                        //
                      })
                    })
                  }
                  break
                }
              }
            }
            // 上传成功回调函数
            that.handleAvatarSuccess(respone, that.currentFile)
          })
          return res
        }).catch(err => {
          console.log('compressErr', err)
        })
      }
    }
  }
</script>

<style scoped>
  .el-upload--picture-card{
    line-height: 0;
  }
</style>

